<template>
  <div>
    <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form :inline="true">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="请输入角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" icon="el-icon-search" @click="getRoleList">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" icon="el-icon-plus" @click="dialogFormVisible = true" v-if="hasAuth('sys:role:save')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm
            title="确定要批量删除角色吗？"
            icon="el-icon-info"
            icon-color="red"
            @confirm="delBatchHandle"
        >
          <el-button size="medium" type="danger" icon="el-icon-delete" slot="reference" :disabled="delBtnStatus" v-if="hasAuth('sys:role:delete')">批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="name"
          label="角色名称"
          width="120">
      </el-table-column>

      <el-table-column
          prop="code"
          label="唯一编码"
          width="120">
      </el-table-column>

      <el-table-column
          prop="remark"
          label="描述"
          show-overflow-tooltip>
      </el-table-column>

      <el-table-column
          prop="status"
          label="状态"
          width="120">
        <template slot-scope="scope">
          <el-tag size="small" type="success" v-if="scope.row.status === 1">正常</el-tag>
          <el-tag size="small" type="danger" v-else-if="scope.row.status === 0">禁用</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          label="操作"
          width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="permHandle(scope.row.id)" v-if="hasAuth('sys:role:perm')">分配权限</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button size="mini" type="primary" @click="editHandle(scope.row.id)" v-if="hasAuth('sys:role:update')">编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <template>
            <el-popconfirm
                title="确定要删除该角色吗？"
                icon="el-icon-info"
                icon-color="red"
                @confirm="delHandle(scope.row.id)"
            >
              <el-button size="mini" type="danger" slot="reference" v-if="hasAuth('sys:role:delete')">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>

    <!--  新增对话框  -->
    <el-dialog title="新增角色" :visible.sync="dialogFormVisible" width="600px" :before-close="handleClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="角色名称" prop="name" label-width="100px">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="唯一编码" prop="code" label-width="100px">
          <el-input v-model="editForm.code" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="remark" label-width="100px">
          <el-input v-model="editForm.remark" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status" label-width="100px">
          <el-radio-group v-model="editForm.status">
            <el-radio :label=0>禁用</el-radio>
            <el-radio :label=1>正常</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('editForm')">提交</el-button>
        <el-button @click="reset('editForm')">重置</el-button>
      </div>
    </el-dialog>

    <!--  分配权限对话框  -->
    <el-dialog title="分配权限" :visible.sync="dialogPermVisible" width="600px">
      <el-form :model="permForm">
        <el-tree
            :data="permTreeData"
            show-checkbox
            ref="permTree"
            :default-expand-all="true"
            node-key="id"
            check-strictly
            :props="defaultProps">
        </el-tree>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogPermVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPermForm('permForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  name: "Role",
  data() {
    return {
      searchForm: {},
      delBtnStatus: true,
      total: 0,
      current: 1,
      size: 10,
      dialogPermVisible: false,
      dialogFormVisible: false,
      editForm: {},
      permForm: {},
      editFormRules: {
        name: [
          {required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入唯一编码', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入描述', trigger: 'blur'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ]
      },
      tableData: [],
      multipleSelection: [], //选中的对象
      permTreeData: [], //权限树形数据
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getRoleList()
    request.get('/sys/menu/list').then(res => {
      this.permTreeData = res.data
    })
  },
  methods: {
    //提交权限
    submitPermForm(formName){
      //获取被选中的菜单id
      let menuIds = this.$refs.permTree.getCheckedKeys()
      request.post('/sys/role/perm/' + this.permForm.id, menuIds).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，分配权限成功',
          type: 'success',
          onClose:() => {
            this.getRoleList()
          }
        })
        this.dialogPermVisible = false
      })
    },
    //获取当前权限
    permHandle(id) {
      this.dialogPermVisible = true
      request.get('/sys/role/info/' + id).then(res => {
        //权限默认赋值
        this.$refs.permTree.setCheckedKeys(res.data.menuIds)
        this.permForm = res.data
      })
    },
    //关闭对话框，清空数据
    handleClose() {
      this.resetForm('editForm')
    },
    //获取角色列表
    getRoleList() {
      request.get("/sys/role/list", {
        params: {
          name: this.searchForm.name,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        this.size = res.data.size
        this.current = res.data.current
      })
    },
    //删除角色项
    delHandle(id) {

      request.post("/sys/role/delete/" + id).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，删除角色成功',
          type: 'success',
          onClose: () => {
            this.getRoleList()
          }
        });
      })
    },
    //获取编辑角色
    editHandle(id) {
      request.get("/sys/role/info/" + id).then(res => {
        //数据回显
        this.editForm = res.data
        //打开对话框
        this.dialogFormVisible = true
      })
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 有id就是修改，否则就是新增
          request.post('/sys/role/' + (this.editForm.id ? "update" : "save"), this.editForm)
              .then(res => {
                this.resetForm(formName)
                //提示信息
                this.$message({
                  showClose: true,
                  message: '恭喜你，编辑角色成功',
                  type: 'success',
                  //关闭这条消息时更新数据
                  onClose: () => {
                    this.getRoleList()
                  }
                });
                //关闭对话框
                this.resetForm('editForm')
                this.dialogFormVisible = false
              })
        } else {
          console.log('提交出错!!');
          return false;
        }
      });
    },
    //重置数据
    reset(formName) {
      this.$refs[formName].resetFields()
      this.editForm = {}
    },
    //清空数据
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.editForm = {}
      this.dialogFormVisible = false
    },
    //关闭弹窗，清除数据
    hadnleClose() {
      this.resetForm('editForm')
    },
    handleSizeChange(val) {
      this.size = val
      this.getRoleList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getRoleList()
    },
    //多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选中的目标
    handleSelectionChange(val) {
      this.multipleSelection = val;

      this.delBtnStatus = val.length <= 0;
    },
    //批量删除
    delBatchHandle() {
      let ids = this.multipleSelection.map(role => role.id)
      request.post("/sys/role/deleteBatch", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，批量删除角色成功',
          type: 'success',
          onClose: () => {
            this.getRoleList()
          }
        });
      })
    }
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 22px;
}
</style>